<template>
  <div class="app-container">
    <el-form class="formList" :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch"
      label-width="88px">
      <el-row>
        <el-form-item label="订单编号" prop="orderNo">
          <el-input v-model="queryParams.orderNo" placeholder="请输入订单编号" clearable size="small" style="width: 232px"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="客户名称" prop="applyNickName">
          <el-input v-model="queryParams.applyNickName" placeholder="请输入客户名称" clearable size="small" style="width: 232px"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="供应商名称" prop="supplierName">
          <el-input v-model="queryParams.supplierName" placeholder="请输入供应商名称" clearable size="small" style="width: 232px"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item label="售后类型" prop="serviceType">
          <el-select v-model="queryParams.serviceType" placeholder="请选择售后类型" clearable size="small" style="width: 232px">
            <el-option v-for="dict in serviceTypeOptions" :key="dict.dictValue" :label="dict.dictLabel"
              :value="dict.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="售后原因" prop="serviceReason">
          <el-select v-model="queryParams.serviceReason" placeholder="请选择售后原因" clearable size="small" style="width: 232px">
            <el-option v-if="queryParams.serviceType && queryParams.serviceType=='refund'"
              v-for="dict in serviceReasonOptions" :key="dict.dictValue" :label="dict.dictLabel"
              :value="dict.dictValue" />

            <el-option v-if="queryParams.serviceType && queryParams.serviceType=='return'"
              v-for="dict in serviceReasonOptionsTwo" :key="dict.dictValue" :label="dict.dictLabel"
              :value="dict.dictValue" />

            <el-option v-if="queryParams.serviceType && queryParams.serviceType=='change'"
              v-for="dict in serviceReasonOptionsThree" :key="dict.dictValue" :label="dict.dictLabel"
              :value="dict.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="申请时间" prop="applyTimeArray">
          <el-date-picker v-model="queryParams.applyTimeArray" type="daterange" align="right" clearable style="width: 232px"
            value-format="yyyy-MM-dd" unlink-panels range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
            :picker-options="pickerOptions">
          </el-date-picker>
        </el-form-item>
        <!-- <el-form-item label="售后状态" prop="dataStatus">
            <el-select v-model="queryParams.dataStatus" placeholder="请选择售后状态" clearable size="small">
              <el-option v-for="dict in dataStatusOptions" :key="dict.dictValue" :label="dict.dictLabel"
                :value="dict.dictValue" />
            </el-select>
          </el-form-item> -->

      </el-row>
      <el-row>
        <el-form-item style="margin-left: 22px;">
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
        </el-form-item>
      </el-row>
    </el-form>

    <el-row class="row-mbinfo">
      <!-- <el-col> -->
        <el-button-group>
          <el-button :class="activeClass == 0 ? 'button-sku-blue':''" @click="handleQueryStatus(0)" size="mini">
            <svg-icon icon-class="product_info_all" />
            <span style="margin-left: 14%;">全部</span>
          </el-button>
          <el-button :class="activeClass == 1 ? 'button-sku-blue':''" @click="handleQueryStatus(1)" size="mini">
            <svg-icon icon-class="order_pending" />
            <span style="margin-left: 14%;">待处理</span>
          </el-button>
          <el-button :class="activeClass == 2 ? 'button-sku-blue':''" @click="handleQueryStatus(2)" size="mini">
            <svg-icon icon-class="order_processing" />
            <span style="margin-left: 14%;">处理中</span>
          </el-button>
          <el-button :class="activeClass == 3 ? 'button-sku-blue':''" @click="handleQueryStatus(3)" size="mini">
            <svg-icon icon-class="order_refuse" />
            <span style="margin-left: 14%;">拒绝售后</span>
          </el-button>
          <el-button :class="activeClass == 4 ? 'button-sku-blue':''" @click="handleQueryStatus(4)" size="mini">
            <svg-icon icon-class="order_agree" />
            <span style="margin-left: 14%;">同意售后</span>
          </el-button>
          <el-button :class="activeClass == 5 ? 'button-sku-blue':''" @click="handleQueryStatus(5)" size="mini">
            <svg-icon icon-class="order_completed" />
            <span style="margin-left: 14%;">售后完成</span>
          </el-button>
          <el-button :class="activeClass == 6 ? 'button-sku-blue':''" @click="handleQueryStatus(6)" size="mini">
            <svg-icon icon-class="order_close" />
            <span style="margin-left: 14%;">取消售后</span>
          </el-button>
        </el-button-group>
      <!-- </el-col> -->

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <div class="divTable">
      <el-table border v-loading="loading" v-if="saleList" :data="saleList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <!-- <el-table-column label="售后ID" align="center" prop="serviceUid" sortable /> -->
        <el-table-column label="订单信息" align="left" prop="orderNo" width="550">
          <template slot-scope="scope">
            <!-- <el-button size="mini" type="text" @click="handleShowDetail(scope.row)">订单编号：{{ scope.row.orderNo }}</el-button> -->
            <div class="item_order_no">订单编号：<el-link type="primary"  @click="handleShowDetail(scope.row)">{{ scope.row.orderNo }}</el-link></div>
            <div class="item_pro_info" v-if="scope.row.item">
              <div style="width:100px;height:100px;margin-right: 10px;" v-if="scope.row.item">
                <el-image v-if="scope.row.item.imgUrl != null && scope.row.item.imgUrl != '' " slot="reference"
                  :src="scope.row.item.imgUrl" class="image-rows" style="width: 100%;height: 100%" :preview-src-list="[scope.row.item.imgUrl]">
                </el-image>
              </div>
              <div class="item_pro_info_txt">
                <div>{{scope.row.item.proName}}</div>
                <div style="line-height: 15px;margin-top: 10px;color: #999">
                  <span style="margin-right:30px;">售价：￥{{scope.row.item.priceStr}}</span>
                  <span style="margin-right:30px;">数量：x{{scope.row.item.itemNumber}}</span>
                  <span>支付：￥{{scope.row.item.itemAmountStr}}</span>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column label="订单编号" align="center" prop="orderNo" :show-overflow-tooltip="true" width="150">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="handleShowDetail(scope.row)">{{ scope.row.orderNo }}
            </el-button>
          </template>
        </el-table-column> -->
        <!-- <el-table-column label="供应商名称" align="left" prop="supplierName" :show-overflow-tooltip="true" width="100"/> -->
        <el-table-column label="售后类型" align="center" prop="serviceType" :formatter="serviceTypeFormat" />
        <el-table-column label="售后原因" align="center" prop="reasonName" width="120" />
        <el-table-column label="售后数量" align="center" prop="serviceNumber" :show-overflow-tooltip="true" />
        <el-table-column label="售后金额(元)" align="center" prop="serviceAmountStr" :show-overflow-tooltip="true"
          width="100" />
        <!-- <el-table-column label="余额(元)" align="center" prop="serviceBalanceStr" :show-overflow-tooltip="true" />
        <el-table-column label="现金(元)" align="center" prop="serviceCashStr" :show-overflow-tooltip="true" /> -->
        <!-- <el-table-column label="图片凭证" align="center" prop="proofImagesOne" :show-overflow-tooltip="true" >
          <template slot-scope="scope">
            <el-image v-if="scope.row.proofImagesOne != null && scope.row.proofImagesOne != '' " slot="reference"
              :src="scope.row.proofImagesOne" class="image-rows" :preview-src-list="[scope.row.proofImagesOne]">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column label="凭证描述" align="center" prop="proofDesc" :show-overflow-tooltip="true" /> -->
        <!-- <el-table-column label="售后状态" align="center" prop="dataStatus" :formatter="dataStatusFormat" width="150"/> -->
        <el-table-column label="客户名称" align="center" prop="applyNickName" :show-overflow-tooltip="true" />
        <!-- <el-table-column label="联系电话" align="center" prop="applyPhone" :show-overflow-tooltip="true" /> -->
        <el-table-column label="申请时间" align="center" prop="applyTime" width="160" sortable>
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.applyTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column v-if="activeClass != 1" label="处理人" align="center" prop="updateName" :show-overflow-tooltip="true" /> -->
        <el-table-column v-if="activeClass != 1" label="处理时间" align="center" prop="updateTime" width="160" sortable>
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="activeClass != 1" label="处理备注" align="center" prop="remark" width="160"
          :show-overflow-tooltip="true" />
        <el-table-column v-if="activeClass != 3 && activeClass != 5 && activeClass != 6" label="操作" align="center" width="100px" fixed="right"
          class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-zoom-in" @click="handleUpdate(scope.row)"
              v-hasPermi="['order:sale:query']" v-if="scope.row.dataStatus == '1'">受理
            </el-button>
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleAudit(scope.row)"
              v-hasPermi="['order:sale:edit']" v-if="scope.row.dataStatus == '2'">审核
            </el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleFinish(scope.row)"
              v-hasPermi="['order:sale:remove']"
              v-if="scope.row.serviceType != 'refund' && scope.row.dataStatus == '4'">收货完结
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </div>

    <!-- 添加或修改订单售后对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body @keyup.enter.native="submitForm">
      <!-- 订单售后信息 -->
      <postSale v-if="showData" :postSale="showData"></postSale>

      <!-- 审核意见 -->
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="余额退款" v-if="form.serviceType =='refund' || form.serviceType == 'return'">
          <el-input v-model="form.serviceBalanceStr"
            @input="form.serviceBalanceStr = oninput(form.serviceBalanceStr, 2)" placeholder="请输入余额" />
        </el-form-item>
        <el-form-item label="现金退款" v-if="form.serviceType =='refund' || form.serviceType == 'return'">
          <el-input v-model="form.serviceCashStr" @input="form.serviceCashStr = oninput(form.serviceCashStr, 2)"
            placeholder="请输入现金" />
        </el-form-item>

        <el-form-item label="处理意见" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入处理意见" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm(true)">同意售后</el-button>
        <el-button type="primary" @click="submitForm(false)">拒绝售后</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看订单售后对话框 -->
    <el-dialog :title="viewTitle" :visible.sync="viewOpen" width="1400px" append-to-body>
      <postSale v-if="showData" :postSale="showData"></postSale>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listSale,
    getSale,
    delSale,
    addSale,
    updateSale,
    auditSale,
  } from "@/api/order/sale";
  import ImageUpload from '@/components/ImageUpload';
  import postSale from "@/components/Order/postSale";


  export default {
    name: "Sale",
    components: {
      ImageUpload,
      postSale,
    },
    data() {
      return {
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }]
        },
        subFlag: true,
        // 默认数字
        activeClass: 0,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 订单售后表格数据
        saleList: [],
        // 弹出层标题
        title: "",
        //查看详细标题
        viewTitle: "",
        // 是否显示弹出层
        open: false,
        //是否显示查看详细弹出层
        viewOpen: false,
        //查看详细数据
        showData: {},
        // 售后类型字典
        serviceTypeOptions: [],
        // 售后原因字典
        serviceReasonOptions: [],
        // 售后原因字典2
        serviceReasonOptionsTwo: [],
        serviceReasonOptionsThree: [],
        // 售后状态字典
        dataStatusOptions: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          orderNo: null,
          supplierName: null,
          serviceType: null,
          serviceReason: null,
          dataStatus: null,
          applyNickName: null,
          applyPhone: null,
          updateName: null,
          updateTime: null,
          applyTimeArray: []
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          remark: [{
            required: true,
            message: "处理意见不能为空",
            trigger: "blur"
          }],
        }
      };
    },
    created() {
      // 默认时间
      let date1 = new Date();
      let date2 = new Date(date1);
      date2.setDate(date1.getDate() - 14);
      let time1 = date1.getFullYear() + "-" + (date1.getMonth() + 1) + "-" + date1.getDate();
      let time2 = date2.getFullYear() + "-" + (date2.getMonth() + 1) + "-" + date2.getDate();
      this.queryParams.applyTimeArray.push(time2);
      this.queryParams.applyTimeArray.push(time1);

      this.getList();
      this.getDicts("order_service_type").then(response => {
        this.serviceTypeOptions = response.data;
      });
      this.getDicts("order_service_refund").then(response => {
        this.serviceReasonOptions = response.data;
      });
      this.getDicts("order_service_return").then(response => {
        this.serviceReasonOptionsTwo = response.data;
      });
      this.getDicts("order_service_change").then(response => {
        this.serviceReasonOptionsThree = response.data;
      });
      this.getDicts("order_service_status").then(response => {
        this.dataStatusOptions = response.data;
      });
    },
    watch: {
      $route(to, from) {
        //from 从哪来
        //to //到哪去
        let path = from.path;
        console.log(path)
        if ("/order/saleDetail/" == path) {
          //刷新页面
          this.getList();
        } else {
          let index = path.lastIndexOf("/");
          if (index > -1) {
            path = path.substr(0, index);
            if ("/order/saleDetail/" == path) {
              //刷新页面
              this.getList();
            }
          }
        }
      }
    },
    methods: {
      handleQueryStatus(index) {
        this.activeClass = index;
        if (index == 0) {
          this.queryParams.dataStatus = null;
        } else if (index == 1) { //待处理
          this.queryParams.dataStatus = "1";
        } else if (index == 2) { //处理中
          this.queryParams.dataStatus = "2";
        } else if (index == 3) { //拒绝售后
          this.queryParams.dataStatus = "3";
        } else if (index == 4) { //同意售后
          this.queryParams.dataStatus = "4";
        } else if (index == 5) { //售后完成
          this.queryParams.dataStatus = "5";
        } else { //取消售后
          this.queryParams.dataStatus = "0";
        }
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 查询订单售后列表 */
      getList() {
        this.saleList = null;
        this.loading = true;
        listSale(this.queryParams).then(response => {
          this.saleList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 售后类型字典翻译
      serviceTypeFormat(row, column) {
        return this.selectDictLabel(this.serviceTypeOptions, row.serviceType);
      },
      // 售后原因字典翻译
      serviceReasonFormat(row, column) {
        return this.selectDictLabel(this.serviceReasonOptions, row.serviceReason);
      },
      // 售后状态字典翻译
      dataStatusFormat(row, column) {
        return this.selectDictLabel(this.dataStatusOptions, row.dataStatus);
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          serviceUid: null,
          orderUid: null,
          orderNo: null,
          itemUid: null,
          supplierUid: null,
          supplierName: null,
          serviceType: null,
          serviceReason: null,
          serviceNumber: null,
          serviceAmount: null,
          serviceBalance: null,
          serviceCash: null,
          proofImages: null,
          proofDesc: null,
          dataStatus: null,
          applyUid: null,
          applyNickName: null,
          applyPhone: null,
          applyTime: null,
          customerAddressUid: null,
          supplierAddressUid: null,
          updateUser: null,
          updateName: null,
          updateTime: null,
          remark: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.activeClass = 0;
        this.resetForm("queryForm");
        this.queryParams.applyTimeArray = null;
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.serviceUid)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加订单售后";
      },
      /** 查看详情按钮操作 **/
      handleShowDetail(row) {
        const serviceUid = row.serviceUid || this.ids
        this.$router.push({
          path: "/order/saleDetail/",
          query: {
            serviceUid: serviceUid,
            type: "0",
          }
        });
        // this.showData = null;
        // const serviceUid = row.serviceUid || this.ids
        // getSale(serviceUid).then(response => {
        //   this.showData = response.data;
        //   console.log(this.showData)
        //   this.viewOpen = true;
        //   this.viewTitle = "查看订单售后";
        // });
      },
      handCloseDetail() {
        this.viewOpen = false
      },
      /** 受理按钮操作 */
      handleUpdate(row) {
        const serviceUid = row.serviceUid || this.ids
        let data = {
          serviceUid: serviceUid,
          dataStatus: '2'
        }
        updateSale(data).then(response => {
          this.msgSuccess("受理成功");
          this.getList();
        });
      },
      //审核
      handleAudit(row) {
        const serviceUid = row.serviceUid || this.ids
        this.$router.push({
          path: "/order/saleDetail/",
          query: {
            serviceUid: serviceUid,
            type: "1",
          }
        });
        // this.reset();
        // this.showData = null;
        // const serviceUid = row.serviceUid || this.ids
        // getSale(serviceUid).then(response => {
        //   this.showData = response.data;
        //   this.form = response.data;
        //   this.open = true;
        //   this.title = "审核";
        // });
      },
      //完结
      handleFinish(row) {
        const serviceUid = row.serviceUid || this.ids
        let data = {
          serviceUid: serviceUid,
          dataStatus: '5'
        }
        updateSale(data).then(response => {
          this.msgSuccess("操作成功");
          this.getList();
        });
      },
      /** 提交按钮 */
      submitForm(flag) {
        this.$refs["form"].validate(valid => {
          if (valid) {

            this.form.serviceBalance = this.form.serviceBalanceStr;
            this.form.serviceCash = this.form.serviceCashStr;

            let amount = parseFloat(this.form.serviceAmountStr);
            let money = parseFloat(this.form.serviceBalance) + parseFloat(this.form.serviceCash);

            if (amount < money) {
              return this.msgError("现金退款+余额退款之和不能大于售后金额！");
            }

            this.form.dataStatus = '3'
            if (flag) {
              this.form.dataStatus = '4'
            }
            if (this.form.serviceUid != null) {
              auditSale(this.form).then(response => {
                this.msgSuccess("操作成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const serviceUids = row.serviceUid || this.ids;
        this.$confirm('是否确认删除订单售后编号为"' + serviceUids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delSale(serviceUids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('order/sale/export', {
          ...this.queryParams
        }, `order_sale.xlsx`)
      },
      oninput(num, limit) {
        var str = num;
        var len1 = str.substr(0, 1);
        var len2 = str.substr(1, 1);
        if (str.length > 1 && len1 == 0 && len2 != ".") {
          str = str.substr(1, 1);
        }
        if (len1 == ".") {
          str = "";
        }
        if (str.indexOf(".") != -1) {
          var str_ = str.substr(str.indexOf(".") + 1);
          if (str_.indexOf(".") != -1) {
            str = str.substr(0, str.indexOf(".") + str_.indexOf(".") + 1);
          }
        }
        //正则替换
        str = str.replace(/[^\d^\.]+/g, ""); // 保留数字和小数点
        if (limit / 1 === 1) {
          str = str.replace(/^\D*([0-9]\d*\.?\d{0,1})?.*$/, "$1"); // 小数点后只能输 1 位
        } else {
          str = str.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/, "$1"); // 小数点后只能输 2 位
        }
        return str;
      },
    }
  };
</script>

<style scoped lang="scss">
  .button-sku-blue {
    color: #409eff;
    background: #ecf5ff;
    border-color: #b3d8ff;
  }
  .item_order_no {
    display: flex;
    align-items: center;
    font-size: 14px;
    margin: 0 0 5px 10px;
    color: #333;
  }
  .item_pro_info {
    display: flex;
    align-items: center;
    font-size: #333;
    .item_pro_info_txt {
      padding: 5px 0;
      flex: 1;
      overflow: hidden;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      min-height: 100px;
    }
  }
</style>
